#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void makestr(TreeNode* node, string& str)
    {
        if (node == nullptr) return;
        str += (std::to_string(node->val));
        str.push_back('(');
        makestr(node->left, str);
        str.push_back(')');
        str.push_back('(');
        makestr(node->right, str);
        if (str.back() != '(')
            str.push_back(')');
        else
        {
            str.pop_back();
            str.pop_back();
            if (str.back() == '(')
                str.pop_back();
            else
                str.push_back(')');
        }
    }
    string tree2str(TreeNode* root) {
        string ret;
        makestr(root, ret);
        return ret;
    }
};